package guicommon.gui;

import guicommon.Body;
import guicommon.Header;
import guicommon.Message;
import guicommon.controls.Control;
import java.awt.Color;
import java.nio.CharBuffer;

public abstract class ControlMessage extends Message {

    public static final String OWNER = "owner";
    public static final String ID = "id";

    public static final String WIDTH = "width";
    public static final String HEIGHT = "height";
    public static final String X = "x";
    public static final String Y = "y";
    public static final String BACKGROUND = "backGround";

    private static Integer counter = 0;

    protected ControlMessage(Header header, CharBuffer buffer) {
        super(header, buffer);
    }

    protected ControlMessage(Class cl, int id) {
        super(Header.FromType(cl, id));
    }

    @Override
    protected void ParseBody(CharBuffer charBuffer) {
        String allPropertiesString = charBuffer.toString();
        String[] properties = allPropertiesString.split(Body.SOH);
        for (String current : properties) {
            String[] pair = current.split("=");
            if (pair.length != 1) {
                AddParseBodyField(pair[0], pair[1]);
            }
        }
    }
    
    public Integer GetIntField(String name) {
        return Integer.valueOf(GetBodyField(name));
    }

    protected Color GetBackGround() {
        return new Color(GetIntField(BACKGROUND));
    }

    public void SetWidth(String message) {
        SetBodyField(WIDTH, message);
    }

    public void SetHeight(String message) {
        SetBodyField(HEIGHT, message);
    }

    public void SetX(String message) {
        SetBodyField(X, message);
    }

    public void SetY(String message) {
        SetBodyField(Y, message);
    }

    public void SetOwner(String message) {
        SetBodyField(OWNER, message);
    }

    public void SetBackGround(String color) {
        SetBodyField(BACKGROUND, color);
    }

    public abstract Control ToControl();

    protected void SetCommonFields(Control result) {
        result.SetPoint(GetIntField(X), GetIntField(Y));
        result.SetSize(GetIntField(WIDTH), GetIntField(HEIGHT));
        result.SetBackGround(GetBackGround());
    }
}
